<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Model\SalesTask;
use MoChat\App\Sales\Model\WorkDepartment;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

/**
 * 会员编辑.
 * @Controller
 */
class Update extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     *
     * @RequestMapping(path="/dashboard/client/update", methods="POST")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $this->validated($data);
        $workEmployeeId = Db::table('work_employee')->where('name', $data['b2bManagerName'])
            ->where('status', 1)
            ->value('id');

        if (isset($data['uniqueId']) && !empty($data['uniqueId'])) {
            $id = Db::table('client')->where('unique_id', $data['uniqueId'])->value('id');
            if ($id !== $data['id']) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '单位内码已存在');
            }
        }

        if (isset($data['enterpriseName']) && !empty($data['enterpriseName'])) {
            $id = Db::table('client')->where('enterprise_name', $data['enterpriseName'])->value('id');
            if ($id && $id !== $data['id']) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '企业名称已存在');
            }
        }
        $client = [
            'unique_id' => $data['uniqueId'] ?? '',
            'enterprise_name' => $data['enterpriseName'],
            'mobile' => $data['mobile'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'b2b_user_type' => $data['b2bUserType'],
            'address' => $data['address'],
            'b2b_register_time' => $data['b2bRegisterTime'],
            'b2b_manager_name' => $data['b2bManagerName'],
            'b2b_salesman_name' => $data['b2bSalesmanName'],
            'is_failure' => $data['is_failure'] ?? 0,//是否失效1是0否
            'failure_remark' => $data['failure_remark'] ?? "",//失效原因
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (isset($data['b2bManagerName']) && !empty($data['b2bManagerName'])) {
            $client['work_employee_id'] = $workEmployeeId ?: 0;
        }
        Db::beginTransaction();
        try {
            Db::table('client')->where('id', $data['id'])->update($client);
            Db::table('client_contact_pivot')->where('client_id', $data['id'])->delete();
            if (!empty($data['contacts'])) {
                $contacts=[];
                foreach ($data['contacts'] as $contact) {
                    if ((isset($contact['id']) && $contact['id']==0) || (isset($contact['is_default']) && $contact['is_default']==1)){
                        $contacts[]=[
                            'client_id' => $data['id'],
                            'name' => $contact['name'],
                            'phone' => $contact['phone'],
                            'is_default'=>1
                        ];
                    }else{
                        $contacts[]=[
                            'client_id' => $data['id'],
                            'name' => $contact['name'],
                            'phone' => $contact['phone'],
                            'is_default'=>0,
                        ];
                    }

                }
                Db::table('client_phone')->where('client_id', $data['id'])->delete();
                Db::table('client_phone')->insert($contacts);
            }else{
                Db::table('client_phone')->where('client_id', $data['id'])->delete();
            }
            Db::commit();

        } catch (\Throwable $throwable) {
            Db::rollBack();
        }
        return [];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'id' => 'required|integer',
            'uniqueId' => 'max:40',
            'enterpriseName' => 'required|max:100',
            'mobile' => 'required|max:20',
            'b2bUserType' => 'required|numeric|in:1,2,3,4',
            'address' => 'required|max:200',
//            'b2bRegisterTime' => 'required',
            'b2bManagerName' => 'max:20',
            'b2bSalesmanName' => 'max:20',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'id.required' => 'id未指定',
            'id.integer' => 'id参数类型错误',
            'enterpriseName.required' => '请填写企业名称',
            'mobile.required' => '请填写手机',
            'b2bUserType.required' => '请填写客户类型',
            'address.required' => '请填写地址',
//            'b2bRegisterTime.required' => '请填写注册时间',
//            'b2bManagerName.required' => '请填写管理员(客服)',
//            'b2bSalesmanName.required' => '请填写业务员',
            'uniqueId.max' => '单位内码长度不能超过40个字符',
            'enterpriseName.max' => '企业名称长度不能超过100个字符',
            'mobile.max' => '手机长度不能超过11个字符',
            'b2bUserType.numeric' => '客户类型格式错误',
            'b2bUserType.in' => '客户类型参数错误',
            'address.max' => '地址长度不能超过200个字符',
            'b2bManagerName.max' => '管理员(客服)长度不能超过20个字符',
            'b2bSalesmanName.max' => '业务员长度不能超过20个字符',
        ];
    }
}
